package com.abu.message.listener;

import cn.hutool.core.util.StrUtil;
import com.abu.common.exception.CRException;
import com.abu.message.utils.QQMailTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import java.util.HashMap;

@Component
@Slf4j
public class CheckMessageRabbitmqListener {


    @Autowired
    private QQMailTemplate mailTemplate;

    private static final String CHECKED_EXCHANGE = "CHECKED_EXCHANGE";
    private static final String CHECKED_ROUTINGKEY = "CHECKED_ROUTINGKEY";
    private static final String CHECKED_QUEUE = "CHECKED_QUEUE";


    /**
     * 通知预定信息
     *
     * @param map
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = CHECKED_EXCHANGE, durable = "true", type = ExchangeTypes.DIRECT),
            value = @Queue(value = CHECKED_QUEUE, durable = "ture", ignoreDeclarationExceptions = "true"),
            key = {CHECKED_ROUTINGKEY}
    ))
    public void receive(HashMap<String, Object> map) {
        String applicant = (String) map.get("applicant");
        String classroomName = (String) map.get("classroomName");
        Integer applyStatus = (Integer) map.get("applyStatus");
        String email = (String) map.get("email");
        String applyStatusStr = "";
        switch (applyStatus) {
            case 1:
                applyStatusStr = "审核已通过";
                break;
            case 2:
                applyStatusStr = "已被驳回";
                break;
            default:
                applyStatusStr = "待审核中";
                break;
        }
//        邮件内容
        String mailText = StrUtil.format("  <div>\n" +
                "    <span style=\"color:green\">{}</span>\n" +
                "    ,您好，您对教室\n" +
                "    <span style=\"color:red\">{}</span>的预约\n" +
                "    <span style=\"color:blue\">{}</span>，更多详情信息请登录系统查看\n" +
                "  </div>", applicant, classroomName, applyStatusStr);
//        邮件主题
        String mailSubject = "<<阿布校理>>";
        try {
            this.mailTemplate.sendHtml(email, mailSubject, mailText);
        } catch (MessagingException e) {
            throw new CRException("发送邮件失败");
        }
    }


}
